package net.rlair.sbdemo.dao.jdbctemplate;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import net.rlair.sbdemo.entity.User;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

/**
 * 用户dao.
 *
 * @author li gu
 */
@Repository
public class LiGuDao {

    @Resource
    private JdbcTemplate jdbcTemplate;

    public Map<String, Object> getAll(final int page, final int pageSize){
        final List<User> userList = jdbcTemplate.query("select * from t_user order by created limit ?,?", (resultSet, i) -> {
            final User user = new User();
            user.setId(resultSet.getInt("id"));
            user.setName(resultSet.getString("name"));
            user.setCreated(resultSet.getDate("created"));
            user.setUpdated(resultSet.getDate("updated"));
            return user;
        }, new Object[]{(page - 1) * pageSize, pageSize});

        final Integer total = jdbcTemplate.queryForObject("select count(*) from t_user", Integer.class);
        final HashMap<String, Object> ret = new HashMap<>();
        ret.put("total", total);
        ret.put("row", userList);
        return ret;
    }
}
